package com.whimscrew.user.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.whimscrew.user.model.Dept;
import com.whimscrew.user.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.Random;

@Service
public class UserService {


    @Autowired
    private DeptService deptService;

    @HystrixCommand(
        //线程池key
        threadPoolKey = "userSaveThreadPool",
        //线程池设置
        threadPoolProperties = {
            @HystrixProperty(name = "coreSize",value="3"),
             //队列大小
            @HystrixProperty(name="maxQueueSize", value="5")
        },
        commandProperties={
            //隔离机制
            @HystrixProperty(name = "execution.isolation.strategy", value = "THREAD") ,
            //超时时间
            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds", value="8000"),
            //连续调用次数的上限值
            @HystrixProperty(name="circuitBreaker.requestVolumeThreshold", value="5"),
            //超过requestVolumeThreshold参数后的失败百分比
            @HystrixProperty(name="circuitBreaker.errorThresholdPercentage", value="50"),
            //快速失败后，需要多长时间恢复系统
            @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds", value="60000"),
            //监视服务问题窗口的时间
            @HystrixProperty(name="metrics.rollingStats.timeInMilliseconds", value="15000"),
            //统计数据收集到5个桶中，长度为3秒（timeInMilliseconds/5）
            @HystrixProperty(name="metrics.rollingStats.numBuckets", value="5")
        }
    )
    public User save(String username) throws InterruptedException {
        Random random = new Random();
        Integer age = random.nextInt(10) + 20;
        User user = new User(username,age  );
        //耗时操作
        Thread.sleep(random.nextInt(3000) );
        //保存和部门的关系
        Dept dept = deptService.saveDept(username);
        Objects.requireNonNull(dept);
        user.setDept(dept);
        return  user;
    }


}
